<template>
  <main-wrap class="wrapper">
    <!-- <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="wrapper"> -->
      <!-- 报修信息块 -->
      <od-info v-if="statcardok"></od-info>

      <ly-tab :items="users" ref="userListWrap"></ly-tab>

      <van-tabs swipeable class="tabWrap">
        <van-tab title="报修单">
          <div class="weui-cells">
            <div class="weui-form-preview__bd">
              <div class="weui-form-preview__item">
                <label class="weui-form-preview__label"><span>地</span><span :class="{'ml2em': ostype === 'IOS'}">址</span></label>
                <span class="weui-form-preview__value">{{addrtext}}</span>
              </div>
              <div class="weui-form-preview__item">
                <label class="weui-form-preview__label black">预约时间</label>
                <span class="weui-form-preview__value apptimewrap">{{apptimestr}}</span>
              </div>
              <div class="weui-form-preview__item">
                <label class="weui-form-preview__label black">故障描述</label>
                <span class="weui-form-preview__value">{{order_detail.desc}}</span>
              </div>
              <div class="weui-form-preview__item">
                <label class="weui-form-preview__label black">上传图片</label>
                <div class="weui-form-preview__value pl0">
                  <my-attachments v-if="showAttachment && order_detail.attachments && order_detail.attachments.length > 0" :attachments="order_detail.attachments" :attachtype="'0'" @fullScreenPlay="fullScreenPlay" @fullScreenStop="fullScreenStop"></my-attachments>
                </div>
              </div>
            </div>
          </div>
        </van-tab>
        <van-tab title="业务流">
          <div class="weui-cells">
            <van-cell-group>
              <van-cell v-for="(item, index) of workList" :key="index">
                <template slot="title">
                  <a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">
                    <div class="weui-media-box__hd">
                      <img class="weui-media-box__thumb" :src="item.tx" alt="">
                    </div>
                    <div class="weui-media-box__bd">
                      <h4 class="weui-media-box__title fullL"><span class="partB">{{item.name}}</span><span class="partS timewrap">{{item.time}}</span></h4>
                      <div class="weui-media-box__desc weui-cell_access" v-if="item.counter">
                        <p>{{item.counter.text}}</p>
                        <time-counter :timer="item.counter.time" :color="'black'" :fsize="'16px'" :tagpos="'right'"></time-counter>
                      </div>
                      <div class="weui-media-box__desc weui-cell_access" v-if="item.text">
                        <p v-if="item.text">{{item.text}}</p>
                        <p v-if="item.desc">{{item.desc}}<span class="van-tag van-tag--round tagred mlp1" v-if="item.showTag">超时</span></p>
                      </div>
                    </div>
                  </a>
                </template>
              </van-cell>
            </van-cell-group>
          </div>
        </van-tab>
        <van-tab title="维修单">
          <div class="weui-cells">
            <div class="weui-form-preview__bd">
              <div class="weui-form-preview__item">
                <label class="weui-form-preview__label black">维修类型</label>
                <span class="weui-form-preview__value">{{rtypetext}}</span>
              </div>
              <div class="weui-form-preview__item">
                <label class="weui-form-preview__label black">维修项目</label>
                <span class="weui-form-preview__value">{{order_detail.repairItemStr}}</span>
              </div>
              <div class="weui-form-preview__item">
                <label class="weui-form-preview__label black">设备编号</label>
                <span class="weui-form-preview__value">{{order_detail.deviceNum}}</span>
              </div>
              <div class="weui-form-preview__item">
                <label class="weui-form-preview__label black">故障描述</label>
                <span class="weui-form-preview__value">{{order_detail.repairDesc}}</span>
              </div>
              <div class="weui-form-preview__item">
                <label class="weui-form-preview__label black">上传图片</label>
                <div class="weui-form-preview__value pl0">
                  <my-attachments v-if="showAttachment && order_detail.attachments && order_detail.attachments.length > 0" :attachments="order_detail.attachments" :attachtype="'1'" @fullScreenPlay="fullScreenPlay" @fullScreenStop="fullScreenStop"></my-attachments>
                </div>
              </div>
            </div>
          </div>
        </van-tab>
      </van-tabs>
    <!-- </van-pull-refresh> -->

    <div class="btnWrap" :class="{'paddingP3': operShow}" ref="btnWrap" v-if="operShow">
      <div class="weui-panel__bd weui-flex" v-if="(ostat === '0' || ostat === '10') && rolecode !== '4' && repairByMe">
        <div class="weui-flex__item" @click="chgApptTime(index)" v-for="(tm, index) in times" :key="index" :class="{'selected': oSelectedTimeIndex === index}">{{tm.str}}</div>
      </div>

      <a href="javascript:;" class="weui-btn weui-btn_primary" @click="goAppoint" v-if="(ostat === '0' || ostat === '10') && rolecode !== '4' && repairByMe">预约</a>
      <router-link to="/mreport" class="weui-btn weui-btn_primary" v-if="ostat === '11' && rolecode !== '4' && repairByMe">填写检修报告</router-link>
      <a href="javascript:;" class="weui-btn weui-btn_primary" @click="goReport" v-if="ostat === '20' && rolecode !== '4' && repairByMe">上报审批</a>
      <router-link to="/mreport" class="weui-btn weui-btn_default" v-if="ostat === '20' && rolecode !== '4' && repairByMe">重新填写</router-link>

      <router-link to="/decision" class="weui-btn weui-btn_primary" v-if="rolecode !== '0' && rolecode !== '4' && ostat === '30' && !repairByMe">批示</router-link>
    </div>

    <my-confirm ref="myconfirm" confirmButtonText="确定" confirmType="info" title="确认" message="上报审批维修报告" descri="" @myes="gotoReport"></my-confirm>
  </main-wrap>
</template>

<script>
import MainWrap from '@/components/mainWrap'
import MyConfirm from '@/components/myconfirm'
import TimeCounter from '@/components/timecounter'
import LyTab from './lytab'
import OdInfo from './odInfo'
import MyAttachments from '@/components/myattachments'
import { mapState, mapActions } from 'vuex'
export default {
  name: 'OrderDetail',
  data () {
    return {
      rolecode: localStorage.rolecode ? localStorage.rolecode : '0',

      refreshing: false,
      statcardok: false, // 刷新状态块所用
      ostat: localStorage.ostat ? localStorage.ostat : '0', // 维修状态
      repairByMe: false,
      operShow: false,
      showAttachment: false,

      // appointOvertimeText: '1天 01:30:09', // 预约超时时间提示文字
      // arriveOvertimeText: '1天 01:30:09', // 上门超时时间提示文字
      appointIn: this.cm.appointOvertime, // 报修后应该在该秒数内预约时间
      appointtimestr: '',
      appointOvertimeText: '',
      arriveOvertimeText: '',

      addrtext: '',
      apptimestr: '',
      rtypetext: '',

      times: [],
      appointTime: '',
      oSelectedTimeIndex: 0,

      users: [],
      workList: []
    }
  },
  components: {
    MainWrap,
    MyConfirm,
    TimeCounter,
    LyTab,
    OdInfo,
    MyAttachments
  },
  computed: {
    ...mapState(['order_detail']),
    ostype () {
      return this.cm.getOSType()
    }
  },
  watch: {
    order_detail () {
      this.statcardok = false
      this.showAttachment = false
      localStorage.ostat = this.order_detail.isReceipt
      this.ostat = this.order_detail.isReceipt
      this.repairByMe = (this.order_detail.repairUserId + '') === sessionStorage.userId
      if (((this.ostat === '0' || this.ostat === '10' || this.ostat === '11' || this.ostat === '20') && this.rolecode !== '4' && this.repairByMe) || (this.rolecode !== '0' && this.rolecode !== '4' && this.ostat === '30' && !this.repairByMe)) {
        this.operShow = true
      }

      let vm = this
      setTimeout(() => {
        vm.statcardok = true
        vm.showAttachment = true
      }, 400)

      this.apptimestr = ''
      this.times = []
      this.users = []
      this.workList = []

      if (this.order_detail.repairDate) {
        this.appointtimestr = this.order_detail.repairDate.slice(0, 10) + ' ' + this.order_detail.repairBeginTime.slice(0, 5) + '-' + this.order_detail.repairEndTime.slice(0, 5)
      }

      if (this.order_detail.acceptRepairTime) {
        let appointOvertime = Math.round(Date.parse(this.order_detail.acceptRepairTime.replace(/-/g, '/')) / 1000) - Math.round(Date.parse(this.order_detail.createTime.replace(/-/g, '/')) / 1000) - this.appointIn
        if (appointOvertime > 0) this.appointOvertimeText = this.cm.gettimestr2(appointOvertime)
      }

      if (this.order_detail.reportTime) {
        let arriveEndTime = this.order_detail.repairDate.slice(0, 10) + ' ' + this.order_detail.repairEndTime
        let arriveOvertime = Math.round(Date.parse(this.order_detail.reportTime.replace(/-/g, '/')) / 1000) - Math.round(Date.parse(arriveEndTime.replace(/-/g, '/')) / 1000)
        if (arriveOvertime > 0) this.arriveOvertimeText = this.cm.gettimestr2(arriveOvertime)
      }

      this.addrtext = this.cm.getBuildingStr(this.order_detail.buildingId) + this.order_detail.address
      this.rtypetext = this.cm.getCategoryStr(this.order_detail.labelId)

      let tarr = this.order_detail.prearrangedTime[0]
      if (tarr) {
        this.apptimestr += tarr.stime1 + '-' + tarr.etime1.substr(11)
        if (tarr.stime2 && tarr.etime2) this.apptimestr += '\n' + tarr.stime2 + '-' + tarr.etime2.substr(11)
        if (tarr.stime3 && tarr.etime3) this.apptimestr += '\n' + tarr.stime3 + '-' + tarr.etime3.substr(11)

        if ((this.ostat === '0' || this.ostat === '10') && this.rolecode !== '4' && this.repairByMe) {
          this.setApptTime(tarr)
        }
      }

      // 报修
      if (this.order_detail.createByUserObj) {
        this.users.push({
          tx: this.cm.getAvatar(this.order_detail.createByUserObj.avatarUrl),
          label: this.order_detail.createByUserObj.name + this.cm.getRoleVal(this.order_detail.createByUserObj.roleValues, ' · '),
          tel: this.order_detail.createByUserObj.mobile
        })

        var reportObj = {
          tx: this.cm.getAvatar(this.order_detail.createByUserObj.avatarUrl),
          name: this.order_detail.createByUserObj.name,
          time: this.order_detail.createTime,
          text: '报修成功'
        }
        this.workList.push(reportObj)
      }

      if (this.order_detail.repairUserObj) {
        this.users.push({
          tx: this.cm.getAvatar(this.order_detail.repairUserObj.avatarUrl),
          label: this.order_detail.repairUserObj.name + this.cm.getRoleVal(this.order_detail.repairUserObj.roleValues, ' · '),
          tel: this.order_detail.repairUserObj.mobile
        })

        var repairUserObj1 = {
          tx: this.cm.getAvatar(this.order_detail.repairUserObj.avatarUrl),
          name: this.order_detail.repairUserObj.name
        }
        // 预约
        if (this.ostat === '0' || this.ostat === '10') {
          repairUserObj1.time = this.order_detail.createTime
          repairUserObj1.counter = {
            text: '剩余预约时间 ',
            time: Math.round(Date.parse(this.order_detail.createTime.replace(/-/g, '/')) / 1000) + this.appointIn
          }
        } else {
          repairUserObj1.time = this.order_detail.acceptRepairTime
          repairUserObj1.text = '预约成功'
          if (this.appointOvertimeText !== '') {
            repairUserObj1.desc = this.appointOvertimeText
            repairUserObj1.showTag = true
          }
        }
        this.workList.push(repairUserObj1)

        // 上门
        if (this.ostat === '11') {
          var repairUserObj2 = {
            tx: this.cm.getAvatar(this.order_detail.repairUserObj.avatarUrl),
            name: this.order_detail.repairUserObj.name
          }
          repairUserObj2.time = this.appointtimestr
          repairUserObj2.counter = {
            text: '剩余上门时间 ',
            time: this.order_detail.repairDate ? Math.round(Date.parse(this.order_detail.repairDate.slice(0, 11).replace(/-/g, '/') + this.order_detail.repairBeginTime) / 1000) : Math.round((new Date()).getTime() / 1000)
          }

          this.workList.push(repairUserObj2)
        } else if (this.ostat !== '0' && this.ostat !== '10' && this.ostat !== '11') {
          var repairUserObj3 = {
            tx: this.cm.getAvatar(this.order_detail.repairUserObj.avatarUrl),
            name: this.order_detail.repairUserObj.name
          }
          repairUserObj3.time = this.order_detail.reportTime
          repairUserObj3.text = '初步检修完成'
          if (this.arriveOvertimeText !== '') {
            repairUserObj3.desc = this.arriveOvertimeText
            repairUserObj3.showTag = true
          }

          this.workList.push(repairUserObj3)
        }
      }

      if (this.order_detail.decisionUserObjList && this.order_detail.decisionUserObjList.length > 0) {
        this.order_detail.decisionUserObjList.reverse()
        for (let m = 0; m < this.order_detail.decisionUserObjList.length; m++) {
          const ele = this.order_detail.decisionUserObjList[m]
          this.users.push({
            tx: this.cm.getAvatar(ele.avatarUrl),
            label: ele.name + this.cm.getRoleVal(ele.roleValues, ' · '),
            tel: ele.mobile
          })

          if (this.order_detail.approvalList && this.order_detail.approvalList.length > 0) {
            for (let n = 0; n < this.order_detail.approvalList.length; n++) {
              const elem = this.order_detail.approvalList[n]
              if (ele.userId === elem.decisionUser) {
                var wlobj = {
                  tx: this.cm.getAvatar(ele.avatarUrl),
                  name: ele.name + this.cm.getRoleVal(ele.roleValues, ' · '),
                  time: elem.decisionTime,
                  text: '批示价格：' + (elem.decisionCost ? elem.decisionCost : 0),
                  desc: '批示意见：' + (elem.decisionDesc ? elem.decisionDesc : '无')
                }
                this.workList.push(wlobj)

                break
              }
            }
          }
        }
      }

      if (this.ostat === '50') {
        if (!(this.repairByMe && this.order_detail.userEvaluate && this.order_detail.userEvaluate.anonymous === '1')) {
          var comobj = {
            tx: this.cm.getAvatar(this.order_detail.createByUserObj.avatarUrl),
            name: this.order_detail.createByUserObj.name,
            time: this.order_detail.userEvaluate.createTime,
            text: '评价：' + this.order_detail.userEvaluate.star + '星' + (this.order_detail.userEvaluate.desc ? '，' + this.order_detail.userEvaluate.desc : '')
          }
          this.workList.push(comobj)
        }
      }

      this.workList.reverse()

      this.$toast.clear()
      this.refreshing = false
    }
  },
  created () {
    this.$toast.loading({
      duration: 0,
      message: '数据获取中...'
    })
    if (this.$route.params.oid) localStorage.oid = this.$route.params.oid
    this.getOrderDetail()
  },
  updated () {
    document.querySelector('.van-tabs__track').style.height = (document.documentElement.clientHeight - 128 - this.$refs.userListWrap.$refs.lytab.clientHeight - 45 - (this.operShow ? this.$refs.btnWrap.clientHeight : 0)) + 'px'
    if (this.operShow) {
      document.querySelector('.van-tabs__track').style.paddingBottom = this.$refs.btnWrap.clientHeight + 'px'
    }
  },
  mounted () {
    this.cm.overscroll(document.querySelector('.van-tabs__track'))
  },
  methods: {
    ...mapActions(['getOrderDetail']),
    goAppoint () {
      this.$toast.loading({
        duration: 0,
        message: '请稍等...'
      })

      let atimes = this.appointTime.split('#')

      this.cm.myajax('/sys/userrepair/staffChckRepairTime', {
        repairId: localStorage.oid,
        repairDate: atimes[0],
        repairStartTime: atimes[1],
        repairEndTime: atimes[2]
      }, (data) => {
        // localStorage.ostat = '11'
        // this.statcardok = false
        // this.$nextTick(() => {
        //   this.statcardok = true
        // })
        // this.ostat = '11'
        this.getOrderDetail()
      })
    },
    goReport () {
      this.$refs.myconfirm.show()
    },
    gotoReport () {
      this.$toast.loading({
        duration: 0,
        message: '请稍等...'
      })

      this.cm.myajax('/sys/userrepair/reportToForeman', {
        repairId: localStorage.oid
      }, (data) => {
        // this.$toast.clear()
        // this.statcardok = false
        // this.$nextTick(() => {
        //   this.statcardok = true
        // })
        // localStorage.ostat = '30'
        // this.ostat = '30'
        this.getOrderDetail()
      })
    },
    onRefresh () {
      this.getOrderDetail()
    },
    fullScreenPlay () {
      if (this.operShow) {
        this.$refs.btnWrap.style.display = 'none'
      }
    },
    fullScreenStop () {
      if (this.operShow) {
        this.$refs.btnWrap.style.display = 'block'
      }
    },
    setApptTime (tarr) {
      let arr = []
      arr.push([new Date(tarr.stime1.replace(/-/g, '/')), new Date(tarr.etime1.replace(/-/g, '/'))])
      arr.push([new Date(tarr.stime2.replace(/-/g, '/')), new Date(tarr.etime2.replace(/-/g, '/'))])
      arr.push([new Date(tarr.stime3.replace(/-/g, '/')), new Date(tarr.etime3.replace(/-/g, '/'))])

      for (let i = 0; i < arr.length; i++) {
        const ele = arr[i]

        let btimestr = this.cm.dealnum(ele[0].getHours()) + ':' + this.cm.dealnum(ele[0].getMinutes())
        let etimestr = this.cm.dealnum(ele[1].getHours()) + ':' + this.cm.dealnum(ele[1].getMinutes())
        let year = ele[0].getFullYear()
        let month = ele[0].getMonth() + 1
        let day = ele[0].getDate()
        this.times.push({
          str: month + '月' + day + '日\n' + btimestr + '-' + etimestr,
          date: year + '-' + month + '-' + day,
          btime: btimestr,
          etime: etimestr
        })
      }

      if (this.times.length > 0) {
        this.appointTime = this.times[0].date + '#' + this.times[0].btime + '#' + this.times[0].etime
      } else {
        this.appointTime = ''
      }
    },
    chgApptTime (i) {
      this.oSelectedTimeIndex = i
      this.appointTime = this.times[i].date + '#' + this.times[i].btime + '#' + this.times[i].etime
    }
  }
}
</script>

<style lang="stylus" scoped>
.wrapper >>> .van-tab
  font-size .32rem
  color black
.wrapper >>> .van-tab--active
  color #467db9
.wrapper >>> .van-tabs__line
  background-color #0082ef
  height 3px
.wrapper >>> .van-tabs__wrap
  border-bottom 1px solid #dfdfdf
.wrapper >>> .van-tabs__track
  overflow auto
.wrapper >>> .van-cell::after
  border-bottom none

.wrapper
  height calc(100vh)
  overflow auto

.weui-cells
  margin-top .24rem
  border-top 1px solid #dfdfdf
  .weui-form-preview__item
    margin-bottom .6em
    font-size .28rem
    .weui-form-preview__label
      color black
    .weui-form-preview__value
      text-align left
      padding-left 1em
    .apptimewrap
      white-space pre-wrap

  .weui-media-box
    padding 0
    padding-top .3rem
    align-items flex-start
    .weui-media-box__hd
      width .68rem
      height .68rem
    .weui-media-box__bd
      .weui-media-box__title
        font-size .3rem
        .timewrap
          color #9b9b9b
          font-size .22rem
      .weui-media-box__desc
        margin-top .24rem
        border-left 2px solid #f5f5f5
        padding-left .2rem
        display block
        p
          line-height .36rem

.btnWrap
  position fixed
  bottom 0
  width calc(100% - .6rem)
  background white
  z-index 10
  .weui-flex
    .weui-flex__item
      text-align center
      white-space pre-wrap
      padding-top 8px
      padding-bottom 5px
      line-height 24px
      color black
      &.selected
        background-color #eeeeee
        color #2F7DCD
.ml2em
  margin-left 2em
</style>
